<?php

namespace App\Models;

use App\Models\BaseModel;
use APp\Models\User;

class Notice extends BaseModel
{
    protected $table = 'notices';

    protected $fillable = [
        'title',
        'type',
        'level',
        'targetType',
        'content',
        'publishStatus',
        'publishId',
        'revokeTime',
        'publishTime',
        'targetUserIds',
    ];

    public function users()
    {
        return $this->belongsToMany(User::class, 'notice_user')->withPivot('is_read');
    }

    // 已读用户
    public function readUsers()
    {
        return $this->users()->wherePivot('is_read', 1);
    }

    // 未读用户
    public function unreadUsers()
    {
        return $this->users()->wherePivot('is_read', 0);
    }

    public function publisher()
    {
        return $this->belongsTo(User::class, 'publishId');
    }

    public function getPublisherNameAttribute()
    {
        return $this->publisher?->nickname ?? null;
    }

    protected $appends = ['publisherName', 'isRead'];

    public function getIsReadAttribute()
    {
        return $this->pivot?->is_read;
    }

    protected $hidden = [
        'publisher',
        'pivot'
    ];

    protected function casts(): array
    {
        return [
            'targetUserIds' => 'json',
            'publishTime'   => 'datetime',
            'revokeTime'    => 'datetime',
        ];
    }
}
